/**
 * 测试新表结构下的副将功能
 */

const http = require('http');
const WebSocket = require('ws');

// 测试配置
const CONFIG = {
    server: {
        host: 'localhost',
        port: 3000,
        protocol: 'http'
    },
    testUser: {
        mobile: '17091271111',
        password: '123456',
        passwordHash: 'e10adc3949ba59abbe56e057f20f883e'
    }
};

class DeputyGeneralTester {
    constructor() {
        this.token = null;
        this.userId = null;
        this.ws = null;
        this.testResults = [];
    }

    async runTest() {
        console.log('🎯 开始测试新表结构下的副将功能...\n');

        try {
            await this.testHttpLogin();
            await this.testWebSocketConnection();
            await this.testDeputyList();
            await this.testDeputyDetail();
            await this.testGenerateDeputy();
            await this.testDisconnect();
            this.printTestResults();
        } catch (error) {
            console.error('❌ 测试过程中发生错误:', error.message);
            this.addTestResult('整体测试', false, error.message);
        }
    }

    async testHttpLogin() {
        console.log('🔐 步骤1: HTTP登录测试...');
        try {
            const loginData = await this.makeHttpRequest('/user-service/user/login', 'POST', {
                mobile: CONFIG.testUser.mobile,
                pwd: CONFIG.testUser.passwordHash
            });

            if (loginData.code === 0 && loginData.data) {
                this.userId = loginData.data.userId;
                this.token = loginData.data.accessToken;
                console.log(`✅ 登录成功: userId=${this.userId}`);
                this.addTestResult('HTTP登录', true, `用户ID: ${this.userId}`);
            } else {
                throw new Error(`登录失败: ${loginData.msg || '未知错误'}`);
            }
        } catch (error) {
            console.log('❌ 登录失败:', error.message);
            this.addTestResult('HTTP登录', false, error.message);
            throw error;
        }
    }

    async testWebSocketConnection() {
        console.log('\n🔌 步骤2: WebSocket连接测试...');
        return new Promise((resolve, reject) => {
            try {
                const wsUrl = `ws://${CONFIG.server.host}:${CONFIG.server.port}/user-service/websocket?t=${this.token}`;
                this.ws = new WebSocket(wsUrl);

                this.ws.on('open', async () => {
                    console.log('✅ WebSocket连接成功');
                    this.addTestResult('WebSocket连接', true, '连接建立成功');
                    this.setupMessageHandler();
                    await this.delay(500);
                    resolve();
                });

                this.ws.on('error', (error) => {
                    console.log('❌ WebSocket连接失败:', error.message);
                    this.addTestResult('WebSocket连接', false, error.message);
                    reject(error);
                });

                setTimeout(() => {
                    if (this.ws.readyState === WebSocket.CONNECTING) {
                        this.ws.close();
                        reject(new Error('连接超时'));
                    }
                }, 10000);
            } catch (error) {
                reject(error);
            }
        });
    }

    setupMessageHandler() {
        this.ws.on('message', (data) => {
            try {
                const message = JSON.parse(data.toString());
                console.log('📨 收到消息:', JSON.stringify(message, null, 2));
            } catch (error) {
                console.error('❌ 消息解析失败:', error.message);
            }
        });
    }

    async testDeputyList() {
        console.log('\n📋 步骤3: 测试副将列表查询(1119)...');
        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                this.ws.removeListener('message', handler);
                console.log('⚠️ 副将列表查询超时');
                this.addTestResult('副将列表查询', false, '请求超时');
                resolve();
            }, 10000);

            const handler = (raw) => {
                try {
                    const msg = JSON.parse(raw.toString());
                    if (msg && msg.act_id === 1119) {
                        clearTimeout(timeout);
                        this.ws.removeListener('message', handler);
                        if (msg.code === 0) {
                            console.log('✅ 副将列表查询成功');
                            console.log(`📊 副将数量: ${msg.list ? msg.list.length : 0}`);
                            if (msg.list && msg.list.length > 0) {
                                console.log('📋 副将列表:', JSON.stringify(msg.list, null, 2));
                            }
                            this.addTestResult('副将列表查询', true, `获取${msg.list ? msg.list.length : 0}个副将`);
                        } else {
                            console.log('❌ 副将列表查询失败:', msg.msg || msg);
                            this.addTestResult('副将列表查询', false, msg.msg || '失败');
                        }
                        return resolve();
                    }
                } catch (_) { }
            };
            this.ws.on('message', handler);
            this.ws.send(JSON.stringify({ c: 1119, d: null }));
        });
    }

    async testDeputyDetail() {
        console.log('\n🔍 步骤4: 测试副将详情查询(1009)...');
        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                this.ws.removeListener('message', handler);
                console.log('⚠️ 副将详情查询超时');
                this.addTestResult('副将详情查询', false, '请求超时');
                resolve();
            }, 10000);

            const handler = (raw) => {
                try {
                    const msg = JSON.parse(raw.toString());
                    if (msg && msg.act_id === 1009) {
                        clearTimeout(timeout);
                        this.ws.removeListener('message', handler);
                        if (msg.code === 0) {
                            console.log('✅ 副将详情查询成功');
                            console.log('📊 副将详情:', JSON.stringify(msg.data, null, 2));
                            this.addTestResult('副将详情查询', true, '查询成功');
                        } else {
                            console.log('❌ 副将详情查询失败:', msg.msg || msg);
                            this.addTestResult('副将详情查询', false, msg.msg || '失败');
                        }
                        return resolve();
                    }
                } catch (_) { }
            };
            this.ws.on('message', handler);
            this.ws.send(JSON.stringify({ c: 1009, d: { id: 1 } }));
        });
    }

    async testGenerateDeputy() {
        console.log('\n🎲 步骤5: 测试副将生成(8765)...');
        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                this.ws.removeListener('message', handler);
                console.log('⚠️ 副将生成超时');
                this.addTestResult('副将生成', false, '请求超时');
                resolve();
            }, 10000);

            const handler = (raw) => {
                try {
                    const msg = JSON.parse(raw.toString());
                    if (msg && msg.act_id === 8765) {
                        clearTimeout(timeout);
                        this.ws.removeListener('message', handler);
                        if (msg.code === 0) {
                            console.log('✅ 副将生成成功');
                            console.log('📊 生成结果:', JSON.stringify(msg.data, null, 2));
                            this.addTestResult('副将生成', true, '生成成功');
                        } else {
                            console.log('❌ 副将生成失败:', msg.msg || msg);
                            this.addTestResult('副将生成', false, msg.msg || '失败');
                        }
                        return resolve();
                    }
                } catch (_) { }
            };
            this.ws.on('message', handler);
            this.ws.send(JSON.stringify({ c: 8765, d: { base_id: 1106, player_id: this.userId } }));
        });
    }

    async testDisconnect() {
        console.log('\n🔌 步骤6: 断开WebSocket连接...');
        if (this.ws) {
            this.ws.close();
        }
        this.addTestResult('断开连接', true, '连接已断开');
    }

    addTestResult(testName, success, message) {
        this.testResults.push({
            test: testName,
            success: success,
            message: message,
            timestamp: new Date().toISOString()
        });
    }

    printTestResults() {
        console.log('\n📊 测试结果汇总:');
        console.log('='.repeat(50));

        let successCount = 0;
        let totalCount = this.testResults.length;

        this.testResults.forEach((result, index) => {
            const status = result.success ? '✅' : '❌';
            console.log(`${index + 1}. ${status} ${result.test}: ${result.message}`);
            if (result.success) successCount++;
        });

        console.log('='.repeat(50));
        console.log(`总计: ${successCount}/${totalCount} 项测试通过`);

        if (successCount === totalCount) {
            console.log('🎉 所有测试通过！新表结构下的副将功能正常！');
        } else {
            console.log('⚠️  部分测试失败，请检查日志');
        }
    }

    async makeHttpRequest(path, method = 'GET', data = null) {
        return new Promise((resolve, reject) => {
            const options = {
                hostname: CONFIG.server.host,
                port: CONFIG.server.port,
                path: path,
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                }
            };

            if (data) {
                const postData = JSON.stringify(data);
                options.headers['Content-Length'] = Buffer.byteLength(postData);
            }

            const req = http.request(options, res => {
                let body = '';
                res.on('data', (chunk) => { body += chunk; });
                res.on('end', () => {
                    try {
                        const responseData = JSON.parse(body);
                        if (res.statusCode >= 200 && res.statusCode < 300) {
                            resolve(responseData);
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}: ${responseData.message || body}`));
                        }
                    } catch (error) {
                        if (res.statusCode >= 200 && res.statusCode < 300) {
                            resolve(body);
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}: ${body}`));
                        }
                    }
                });
            });

            req.on('error', (error) => { reject(error); });
            if (data) { req.write(JSON.stringify(data)); }
            req.end();
        });
    }

    async delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

async function main() {
    const tester = new DeputyGeneralTester();
    await tester.runTest();
}

if (require.main === module) {
    main().catch((error) => {
        console.error('💥 测试脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = DeputyGeneralTester;
